<script>
export default {
  name: "index",
  data() {
    return {
      // 地图基本属性
      center: {
        lat: 22.0191115805705,
        lng: 113.711184976166
      },
      scale: 12,
      minScale: 10,
      maxScale: 19,
      enableRotate: false,
      enableOverlooking: false,
      enableZoom: true,
      enableScroll: true,
      showLocation: true,
      showCompass: true,
      showScale: true,
      enableSatellite: false,

      // 瓦片相关
      tileCacheSize: 100, // 缓存大小
      tileCache: new Map(), // 瓦片缓存
      visibleTiles: [], // 可见瓦片
      tileServerUrl: 'https://wzws.wanshanlundiao.cn/tilesMap', // 瓦片服务器路径
      nameFormat: "{x}_{y}", // 瓦片名称格式
      tileExt: ".png", // 瓦片扩展名
      useLocalTiles: true, // 使用本地瓦片
      addedOverlays: [], // 已添加的覆盖物ID列表

      // 地图边界和区域信息
      mapRegion: null,

      // 地图状态
      isMapLoaded: false,
      loadError: false,
      debugInfo: {
        visibleTilesCount: 0,
        cachedTilesCount: 0,
        currentZoom: 12,
        mapRegion: null,
        lastUpdate: null
      },

      // 标记点
      markers: [
        {
          id: 0,
          latitude: 22.0191115805705,
          longitude: 113.711184976166,
          title: '东澳岛',
          iconPath: 'https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/marker.png',
          width: 30,
          height: 30,
          anchor: {
            x: 0.5,
            y: 1
          },
          callout: {
            content: '东澳岛',
            color: '#000000',
            fontSize: 14,
            borderRadius: 4,
            borderWidth: 1,
            borderColor: '#CCCCCC',
            bgColor: '#FFFFFF',
            padding: 5,
            display: 'BYCLICK'
          }
        }
      ],

      // 地图上下文
      mapContext: null,
      isUpdating: false,

      // 调试网格
      showGrid: true, // 是否显示瓦片网格
      gridColor: 'rgba(255, 0, 0, 0.5)', // 网格颜色
      gridWidth: 2, // 网格线宽度
      polylines: [], // 多边形线条
    }
  },
  computed: {
    mapStyle() {
      return this.enableSatellite ? 'satellite' : 'normal';
    },
    displayDebugInfo() {
      return {
        visibleTiles: this.visibleTiles.length,
        cachedTiles: this.tileCache.size,
        scale: this.scale,
        center: `${this.center.lng.toFixed(6)}, ${this.center.lat.toFixed(6)}`,
        lastUpdate: this.debugInfo.lastUpdate ? new Date(this.debugInfo.lastUpdate).toLocaleTimeString() : 'None'
      };
    }
  },
  mounted() {
    this.initMap();
  },
  beforeDestroy() {
    // 清除所有添加的瓦片覆盖物
    this.removeAllGroundOverlays();

    // 清除缓存
    this.tileCache.clear();
  },
  methods: {
    // 初始化地图
    initMap() {
      this.$nextTick(() => {
        try {
          this.mapContext = uni.createMapContext('myMap', this);
          console.log('地图上下文创建成功');
          this.isMapLoaded = true;

          // 初始化加载瓦片
          this.updateVisibleTiles();
        } catch (error) {
          console.error('初始化地图失败:', error);
          this.loadError = true;
        }
      });
    },

    // 添加地面覆盖物
    addGroundOverlay(tile) {
      if (!this.mapContext) {
        console.error('地图上下文不存在，无法添加瓦片');
        return Promise.reject('地图上下文不存在');
      }

      // 检查ID是否已经存在于已添加列表中
      if (this.addedOverlays.includes(tile.id)) {
        console.warn(`覆盖物ID ${tile.id} 已存在，跳过添加`);
        return Promise.resolve({ errMsg: "addGroundOverlay:ok (skipped)" });
      }

      return new Promise((resolve, reject) => {
        // 添加地面覆盖物
        this.mapContext.addGroundOverlay({
          id: tile.id,
          src: tile.url,
          bounds: tile.bounds,
          visible: true,
          opacity: 1,
          zIndex: 100,
          success: (res) => {
            console.log(`添加地面覆盖物成功: ${tile.id}`, res);
            // 记录已添加的覆盖物ID
            this.addedOverlays.push(tile.id);
            resolve(res);
          },
          fail: (err) => {
            console.error(`添加地面覆盖物失败: ${tile.id}`, err);
            reject(err);
          }
        });
      });
    },

    // 移除地面覆盖物
    removeGroundOverlay(id) {
      if (!this.mapContext) return Promise.reject('地图上下文不存在');

      // 检查ID是否存在于已添加列表中
      if (!this.addedOverlays.includes(id)) {
        console.warn(`覆盖物ID ${id} 不存在，跳过移除`);
        return Promise.resolve({ errMsg: "removeGroundOverlay:ok (skipped)" });
      }

      return new Promise((resolve, reject) => {
        this.mapContext.removeGroundOverlay({
          id: id,
          success: (res) => {
            console.log(`移除地面覆盖物成功: ${id}`, res);
            // 从已添加列表中移除
            const index = this.addedOverlays.indexOf(id);
            if (index !== -1) {
              this.addedOverlays.splice(index, 1);
            }
            resolve(res);
          },
          fail: (err) => {
            console.error(`移除地面覆盖物失败: ${id}`, err);
            // 即使失败也从列表中移除，防止后续操作出错
            const index = this.addedOverlays.indexOf(id);
            if (index !== -1) {
              this.addedOverlays.splice(index, 1);
            }
            reject(err);
          }
        });
      });
    },

    // 移除所有地面覆盖物
    removeAllGroundOverlays() {
      if (this.addedOverlays.length === 0) {
        return Promise.resolve();
      }

      // 创建副本进行操作，避免在迭代过程中修改原数组
      const overlaysToRemove = [...this.addedOverlays];
      const promises = overlaysToRemove.map(id => this.removeGroundOverlay(id));

      return Promise.all(promises).catch(err => {
        console.error('移除所有地面覆盖物失败', err);
      }).finally(() => {
        // 确保覆盖物ID列表被清空
        this.addedOverlays = [];
      });
    },

    // 地图区域变化事件处理
    onRegionChange(e) {
      // 仅处理结束事件
      if (e.type === 'end') {
        console.log('地图区域变化:', e);

        if (e.causedBy === 'drag' && e.detail && e.detail.centerLocation) {
          // 更新中心坐标
          this.center = {
            lat: e.detail.centerLocation.latitude,
            lng: e.detail.centerLocation.longitude
          };
        }

        if (e.causedBy === 'scale' && e.detail && e.detail.scale) {
          // 更新缩放级别并确保是整数
          const intScale = Math.round(e.detail.scale);
          if (this.scale !== intScale) {
            this.scale = intScale;
            // 通过mapContext设置整数缩放值
            if (this.mapContext) {
              this.mapContext.moveToLocation({
                latitude: this.center.lat,
                longitude: this.center.lng,
                scale: intScale
              });
            }
          }
        }

        // 直接更新瓦片
        this.updateVisibleTiles();
      }
    },

    // 获取地图可视区域
    getMapRegion() {
      return new Promise((resolve, reject) => {
        if (!this.mapContext) {
          reject(new Error('地图上下文不存在'));
          return;
        }

        this.mapContext.getRegion({
          success: (res) => {
            this.mapRegion = {
              southwest: res.southwest,
              northeast: res.northeast
            };
            resolve(this.mapRegion);
          },
          fail: (err) => {
            console.error('获取地图区域失败:', err);
            reject(err);
          }
        });
      });
    },

    // 经纬度转瓦片坐标 - 使用腾讯地图的计算方式
    latLngToTile(lat, lng, zoom) {
      // 使用与腾讯地图一致的计算方法
      try {
        // 腾讯地图的计算逻辑
        const n = Math.pow(2, zoom);
        const x = Math.floor(((lng + 180) / 360) * n);
        const latRad = lat * Math.PI / 180;
        const y = Math.floor((1 - Math.log(Math.tan(latRad) + 1 / Math.cos(latRad)) / Math.PI) / 2 * n);

        console.log(`经纬度(${lat}, ${lng}) 转瓦片坐标: ${x}, ${y}, 缩放级别: ${zoom}`);
        return { x, y };
      } catch (error) {
        console.error('经纬度转瓦片坐标失败:', error);
        return { x: 0, y: 0 };
      }
    },

    // 瓦片坐标转经纬度边界
    getTileBounds(x, y, zoom) {
      const n = Math.pow(2, zoom);

      const west = x / n * 360 - 180;
      const east = (x + 1) / n * 360 - 180;

      const north = Math.atan(Math.sinh(Math.PI * (1 - 2 * y / n))) * 180 / Math.PI;
      const south = Math.atan(Math.sinh(Math.PI * (1 - 2 * (y + 1) / n))) * 180 / Math.PI;

      console.log(`瓦片坐标(${x}, ${y}, ${zoom}) 边界: 西${west.toFixed(6)}, 东${east.toFixed(6)}, 南${south.toFixed(6)}, 北${north.toFixed(6)}`);

      return {
        southwest: {
          latitude: south,
          longitude: west
        },
        northeast: {
          latitude: north,
          longitude: east
        }
      };
    },

    // 获取瓦片URL - 严格按照map_v2.html的逻辑
    getTileUrl(zoom, x, y) {
      try {
        // 严格按照map_v2.html的逻辑生成URL
        const name = this.nameFormat
            .replace("{x}", x)
            .replace("{y}", y)
            .replace("{z}", zoom);

        // 使用原始逻辑: 'tiles/' + zoom + '/' + name + ext
        const url = `${this.tileServerUrl}/tiles/${zoom}/${name}${this.tileExt}`;

        console.log(`生成瓦片URL: ${url}, x=${x}, y=${y}, zoom=${zoom}`);
        return url;
      } catch (error) {
        console.error('生成瓦片URL失败:', error);
        return '';
      }
    },

    // 调试用 - 测试瓦片可访问性
    async testTileUrl(url) {
      return new Promise((resolve) => {
        uni.request({
          url: url,
          method: 'HEAD',
          success: (res) => {
            const success = res.statusCode >= 200 && res.statusCode < 300;
            console.log(`测试瓦片URL ${url}: ${success ? '成功' : '失败'} (${res.statusCode})`);
            resolve(success);
          },
          fail: (err) => {
            console.error(`测试瓦片URL ${url} 失败:`, err);
            resolve(false);
          }
        });
      });
    },

    // 检查图片是否可访问
    checkImageAccessible(url) {
      return new Promise((resolve) => {
        uni.request({
          url: url,
          method: 'HEAD',
          success: (res) => {
            if (res.statusCode >= 200 && res.statusCode < 300) {
              resolve(true);
            } else {
              console.warn(`图片访问失败，状态码: ${res.statusCode}`, url);
              resolve(false);
            }
          },
          fail: () => {
            console.warn(`图片访问失败`, url);
            resolve(false);
          }
        });
      });
    },

    // 添加地面覆盖物前先检查图片是否可访问
    async addGroundOverlayWithCheck(tile) {
      try {
        // 先检查图片是否可以访问
        const isAccessible = await this.checkImageAccessible(tile.url);

        if (!isAccessible) {
          console.error(`瓦片图片无法访问: ${tile.url}`);
          return Promise.reject('图片资源不可访问');
        }

        return this.addGroundOverlay(tile);
      } catch (error) {
        console.error('添加覆盖物检查失败:', error);
        return Promise.reject(error);
      }
    },

    // 管理瓦片缓存
    manageTileCache() {
      // 如果缓存超过上限，移除最早加入的瓦片
      if (this.tileCache.size > this.tileCacheSize) {
        const keysToDelete = Array.from(this.tileCache.keys()).slice(0, this.tileCache.size - this.tileCacheSize);
        keysToDelete.forEach(key => {
          this.tileCache.delete(key);
        });
      }
    },

    // 切换地图类型
    toggleMapType() {
      this.enableSatellite = !this.enableSatellite;
    },

    // 移动到用户位置
    moveToLocation() {
      if (!this.mapContext) return;

      this.mapContext.moveToLocation({
        success: () => {
          console.log('移动到我的位置成功');
        },
        fail: (err) => {
          console.error('移动到我的位置失败:', err);
        }
      });
    },

    // 地图点击事件
    onMapTap(e) {
      console.log('地图点击:', e);
    },

    // 标记点点击事件
    onMarkerTap(e) {
      const markerId = e.detail.markerId;
      console.log('标记点点击:', markerId);

      const marker = this.markers.find(item => item.id === markerId);
      if (marker) {
        this.center = {
          lat: marker.latitude,
          lng: marker.longitude
        };
      }
    },

    // 刷新地图瓦片
    refreshTiles() {
      // 清除缓存
      this.tileCache.clear();
      // 更新瓦片
      this.updateVisibleTiles();
    },

    // 地图加载完成事件
    onMapReady(e) {
      console.log('地图加载完成:', e);
      this.isMapLoaded = true;
      this.loadError = false;

      // 初始加载瓦片
      this.updateVisibleTiles();
    },

    // 地图加载错误事件
    onMapError(e) {
      console.error('地图加载错误:', e);
      this.loadError = true;
    },

    // 重新加载地图
    reloadMap() {
      this.isMapLoaded = false;
      this.loadError = false;
      this.tileCache.clear();

      // 移除所有瓦片
      this.removeAllGroundOverlays();

      this.$nextTick(() => {
        this.initMap();
      });
    },

    // 计算可见瓦片 - 参考腾讯地图的计算方式
    calculateVisibleTiles(region, zoom) {
      try {
        // 将经纬度转换为瓦片坐标
        const southWestTile = this.latLngToTile(region.southwest.latitude, region.southwest.longitude, zoom);
        const northEastTile = this.latLngToTile(region.northeast.latitude, region.northeast.longitude, zoom);

        // 计算瓦片范围，包括部分显示的瓦片
        const minX = Math.floor(Math.min(southWestTile.x, northEastTile.x));
        const maxX = Math.ceil(Math.max(southWestTile.x, northEastTile.x));
        const minY = Math.floor(Math.min(southWestTile.y, northEastTile.y));
        const maxY = Math.ceil(Math.max(southWestTile.y, northEastTile.y));

        console.log(`瓦片范围: X=${minX}-${maxX}, Y=${minY}-${maxY}, 缩放级别=${zoom}`);

        // 扩大范围，确保边缘部分也被加载
        const expandedMinX = Math.max(0, minX - 1);
        const expandedMaxX = maxX + 1;
        const expandedMinY = Math.max(0, minY - 1);
        const expandedMaxY = maxY + 1;

        // 限制瓦片数量，防止请求过多
        const maxTilesPerRequest = 16; // 增加允许的瓦片数量

        const tiles = [];

        // 生成瓦片 - 使用数字ID
        let idCounter = 2000; // 起始ID

        // 创建包含所有可能瓦片的映射
        const tileMap = {};

        // 按照腾讯地图的方式循环生成瓦片
        for (let x = expandedMinX; x <= expandedMaxX; x++) {
          for (let y = expandedMinY; y <= expandedMaxY; y++) {
            // 瓦片坐标
            const tileKey = `${zoom}_${x}_${y}`;

            // 检查缓存
            if (this.tileCache.has(tileKey)) {
              const tile = this.tileCache.get(tileKey);
              tileMap[tileKey] = tile;
              tiles.push(tile);

              // 限制瓦片数量
              if (tiles.length >= maxTilesPerRequest) break;
              continue;
            }

            // 创建新瓦片
            const bounds = this.getTileBounds(x, y, zoom);
            const url = this.getTileUrl(zoom, x, y);

            const tile = {
              id: idCounter++,
              url: url,
              bounds: bounds,
              x: x,
              y: y,
              zoom: zoom,
              tileKey: tileKey
            };

            // 添加到缓存
            this.tileCache.set(tileKey, tile);
            tileMap[tileKey] = tile;

            // 添加到可见瓦片
            tiles.push(tile);

            // 限制瓦片数量
            if (tiles.length >= maxTilesPerRequest) break;
          }

          // 限制瓦片数量
          if (tiles.length >= maxTilesPerRequest) break;
        }

        // 缓存管理
        this.manageTileCache();

        console.log(`计算完成，共生成${tiles.length}个瓦片`);
        return tiles;
      } catch (error) {
        console.error('计算可见瓦片失败:', error);
        return [];
      }
    },

    // 更新可见瓦片
    async updateVisibleTiles() {
      if (this.isUpdating) return;

      this.isUpdating = true;

      try {
        // 获取地图可视区域
        const region = await this.getMapRegion();

        // 获取当前缩放级别 - 确保使用整数缩放值
        const zoom = Math.round(this.scale);
        if (zoom < this.minScale || zoom > this.maxScale) {
          // 如果缩放级别超出范围，清空所有瓦片
          await this.removeAllGroundOverlays();
          this.visibleTiles = [];
          this.isUpdating = false;
          return;
        }

        console.log('当前缩放级别:', zoom);

        // 计算新的可见瓦片
        const newTiles = this.calculateVisibleTiles(region, zoom);

        // 找出需要添加和需要删除的瓦片
        const currentTileKeys = this.visibleTiles.map(tile => tile.tileKey);
        const newTileKeys = newTiles.map(tile => tile.tileKey);

        // 需要删除的瓦片：当前显示但不在新计算结果中的瓦片
        const tilesToRemove = this.visibleTiles.filter(tile =>
            !newTileKeys.includes(tile.tileKey)
        );

        // 需要添加的瓦片：新计算结果中但不在当前显示的瓦片
        const tilesToAdd = newTiles.filter(tile =>
            !currentTileKeys.includes(tile.tileKey)
        );

        console.log(`瓦片更新: 当前${this.visibleTiles.length}个, 新计算${newTiles.length}个, 需要移除${tilesToRemove.length}个, 需要添加${tilesToAdd.length}个`);

        // 先删除不需要的瓦片
        if (tilesToRemove.length > 0) {
          const removePromises = tilesToRemove.map(tile => this.removeGroundOverlay(tile.id));
          await Promise.allSettled(removePromises);
        }

        // 添加新的瓦片 - 一次只处理一个瓦片，避免并发问题
        for (const tile of tilesToAdd) {
          console.log(`准备加载瓦片: ID=${tile.id}, URL=${tile.url}, 坐标=${tile.x},${tile.y}`);

          try {
            await this.addGroundOverlay(tile);
            console.log(`瓦片 ${tile.x},${tile.y} (ID:${tile.id}) 加载成功`);
          } catch (error) {
            console.error(`瓦片 ${tile.x},${tile.y} (ID:${tile.id}) 加载失败:`, error);
          }

          // 添加短暂延迟，避免请求过快
          await new Promise(resolve => setTimeout(resolve, 100));
        }

        // 更新可见瓦片列表
        this.visibleTiles = newTiles;

        // 更新调试信息
        this.debugInfo.visibleTilesCount = newTiles.length;
        this.debugInfo.cachedTilesCount = this.tileCache.size;
        this.debugInfo.currentZoom = zoom;
        this.debugInfo.mapRegion = region;
        this.debugInfo.lastUpdate = Date.now();

        // 如果启用了网格，更新网格显示
        if (this.showGrid) {
          this.updateTileGrid(newTiles);
        }

        console.log(`更新可见瓦片完成: 共${newTiles.length}个瓦片, 缩放级别: ${zoom}`);
      } catch (error) {
        console.error('更新可见瓦片失败:', error);
      } finally {
        this.isUpdating = false;
      }
    },

    // 更新瓦片网格
    updateTileGrid(tiles) {
      // 移除当前的所有网格线
      this.removeAllPolylines();

      // 为每个瓦片添加网格边框
      tiles.forEach(tile => {
        this.addTileGridLine(tile);
      });
    },

    // 添加瓦片网格线
    addTileGridLine(tile) {
      if (!this.mapContext) return;

      // 从瓦片边界获取角点坐标
      const { southwest, northeast } = tile.bounds;

      // 创建矩形的四个角点
      const sw = { latitude: southwest.latitude, longitude: southwest.longitude };
      const se = { latitude: southwest.latitude, longitude: northeast.longitude };
      const ne = { latitude: northeast.latitude, longitude: northeast.longitude };
      const nw = { latitude: northeast.latitude, longitude: southwest.longitude };

      // 创建闭合矩形的点序列
      const points = [sw, se, ne, nw, sw];

      // 创建多边形线
      const polylineId = `grid_${tile.id}`;
      this.mapContext.addPolyline({
        points: points,
        color: this.gridColor,
        width: this.gridWidth,
        dottedLine: true,
        arrowLine: false,
        id: polylineId,
        success: () => {
          this.polylines.push(polylineId);
        },
        fail: (err) => {
          console.error('添加网格线失败:', err);
        }
      });

      // 在瓦片中心添加标签，显示瓦片坐标和URL
      const centerLat = (southwest.latitude + northeast.latitude) / 2;
      const centerLng = (southwest.longitude + northeast.longitude) / 2;

      // 添加坐标标记
      this.mapContext.addMarkers({
        markers: [{
          id: 10000 + tile.id, // 确保不与其他标记冲突
          latitude: centerLat,
          longitude: centerLng,
          width: 100,
          height: 30,
          callout: {
            content: `${tile.x}_${tile.y} (${tile.zoom}层)`,
            color: '#000000',
            fontSize: 10,
            borderRadius: 2,
            borderWidth: 1,
            borderColor: '#FFFFFF',
            bgColor: 'rgba(255,255,255,0.7)',
            padding: 2,
            display: 'ALWAYS'
          }
        }],
        success: () => {},
        fail: (err) => {
          console.error('添加瓦片坐标标记失败:', err);
        }
      });
    },

    // 移除所有多边形线
    removeAllPolylines() {
      if (!this.mapContext || this.polylines.length === 0) return;

      // 移除所有瓦片网格线
      this.polylines.forEach(id => {
        this.mapContext.removePolyline({
          id: id,
          success: () => {},
          fail: () => {}
        });
      });

      // 移除所有瓦片坐标标记
      this.mapContext.removeMarkers({
        markerIds: this.visibleTiles.map(tile => 10000 + tile.id),
        success: () => {},
        fail: () => {}
      });

      // 清空多边形线列表
      this.polylines = [];
    },

    // 切换瓦片网格显示
    toggleGrid() {
      this.showGrid = !this.showGrid;

      if (this.showGrid) {
        // 如果启用网格，更新显示
        this.updateTileGrid(this.visibleTiles);
      } else {
        // 如果禁用网格，移除所有网格线
        this.removeAllPolylines();
      }
    },

    // 切换本地/在线瓦片
    toggleTileSource() {
      this.useLocalTiles = !this.useLocalTiles;
      console.log(`瓦片源切换为: ${this.useLocalTiles ? '本地瓦片' : '在线瓦片'}`);
      this.tileCache.clear();
      this.updateVisibleTiles();
    },
  }
}
</script>

<template>
  <view class="map-container">
    <!-- 地图组件 -->
    <map
        id="myMap"
        :latitude="center.lat"
        :longitude="center.lng"
        :scale="scale"
        :min-scale="minScale"
        :max-scale="maxScale"
        :show-location="showLocation"
        :enable-rotate="enableRotate"
        :enable-overlooking="enableOverlooking"
        :enable-zoom="enableZoom"
        :enable-scroll="enableScroll"
        :show-compass="showCompass"
        :show-scale="showScale"
        :markers="markers"
        style="width: 100%; height: 100%;"
        :layer-style="1"
        :map-style="mapStyle"
        subkey="AHTBZ-2PHLA-WHOKR-CJ5ZK-OZ5JV-H7BDN"
        @regionchange="onRegionChange"
        @updated="onMapReady"
        @error="onMapError"
        @tap="onMapTap"
        @markertap="onMarkerTap"
    >
    </map>

    <!-- 错误提示 -->
    <view v-if="loadError" class="error-overlay">
      <view class="error-message">地图加载失败</view>
      <button class="reload-button" @tap="reloadMap">重试</button>
    </view>

    <!-- 地图控制按钮 -->
    <view class="map-controls">
      <button class="map-control-button" @tap="toggleMapType">
        {{enableSatellite ? '标准地图' : '卫星地图'}}
      </button>
      <button class="map-control-button" @tap="moveToLocation">
        我的位置
      </button>
      <button class="map-control-button" @tap="refreshTiles">
        刷新瓦片
      </button>
      <button class="map-control-button" @tap="toggleGrid">
        {{showGrid ? '隐藏网格' : '显示网格'}}
      </button>
      <button class="map-control-button" @tap="toggleTileSource">
        {{useLocalTiles ? '使用在线瓦片' : '使用本地瓦片'}}
      </button>
    </view>

    <!-- 调试信息显示 -->
    <view v-if="isMapLoaded && !loadError" class="map-info">
      <text>缩放: {{displayDebugInfo.scale}}</text>
      <text>瓦片: {{displayDebugInfo.visibleTiles}}</text>
      <text>缓存: {{displayDebugInfo.cachedTiles}}</text>
      <text>来源: {{useLocalTiles ? '本地' : '在线'}}</text>
    </view>
  </view>
</template>

<style scoped lang="scss">
.map-container {
  position: relative;
  width: 100%;
  height: 100vh;

  .error-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    background-color: rgba(255, 255, 255, 0.9);
    z-index: 1000;

    .error-message {
      font-size: 16px;
      color: #e74c3c;
      margin-bottom: 15px;
    }

    .reload-button {
      padding: 8px 16px;
      background-color: #3498db;
      color: white;
      border: none;
      border-radius: 4px;
      cursor: pointer;

      &:hover {
        background-color: #2980b9;
      }
    }
  }

  .map-controls {
    position: absolute;
    top: 10px;
    right: 10px;
    z-index: 900;
    display: flex;
    flex-direction: column;

    .map-control-button {
      padding: 8px 12px;
      margin-bottom: 10px;
      background-color: white;
      border: 1px solid #ccc;
      border-radius: 4px;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
      cursor: pointer;
      font-size: 12px;
    }
  }

  .map-info {
    position: fixed;
    bottom: 10px;
    left: 50%;
    transform: translateX(-50%);
    background-color: rgba(0, 0, 0, 0.5);
    color: #fff;
    padding: 5px 10px;
    border-radius: 4px;
    font-size: 12px;
    z-index: 900;

    text {
      margin: 0 5px;
    }
  }
}
</style>